//
//  EpointTestFuctionViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-1-22.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointTestFuctionViewController.h"
#import "ATMHud.h"
#import "EpointAVCallViewController.h"
#import "EpointCDViewController.h"
#import "EpointPerson.h"
#import "EpointTestiChartjsViewController.h"
#import "DetailViewController.h"
#import "EpointMutiPickerViewController.h"

@interface EpointTestFuctionViewController ()
{
    UITableView *tv;
    NSMutableArray *dataArray;
    ATMHud *hud;
    
    NSString *name;
    ASINetworkQueue *_queue;
    ASIHTTPRequest *_request;
    
    SGdownloader* sgdownload;
}
@end

@implementation EpointTestFuctionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dataArray = [[NSMutableArray alloc]init];
        [dataArray addObject:@"ATM进度条"];
        [dataArray addObject:@"ASIHttp文件下载"];
        [dataArray addObject:@"SGDownload文件下载"];
        [dataArray addObject:@"视频捕获"];
        [dataArray addObject:@"添加意见"];
        [dataArray addObject:@"window"];
        [dataArray addObject:@"contacts"];
        [dataArray addObject:@"SQLITE PERSISTENCE OBJECT"];
        [dataArray addObject:@"ichartjs"];
        [dataArray addObject:@"多选示例"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    if (!_queue) {
        _queue = [[ASINetworkQueue alloc] init];
        _queue.showAccurateProgress = YES;
        _queue.shouldCancelAllRequestsOnFailure = NO;
        [_queue go];
    }
    
    hud = [[ATMHud alloc]init];
    hud.delegate = self;
    
    
    tv = [[UITableView alloc]initWithFrame:[self getFullContentFrame]];
    
    tv.dataSource = self;
    tv.delegate = self;
    tv.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tv];
    
    [self.view addSubview:hud.view];
    
    sgdownload = [[SGdownloader alloc]initWithURL:[NSURL URLWithString:@"http://code4app.com/down/36ea7fc43154ad592477a545717abbec/?id=5294c3cdcb7e8450688b4d0a"] timeout:20];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"simplecell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]init];
    }
    cell.backgroundColor = [UIColor clearColor];
    NSString *m = [dataArray objectAtIndex:indexPath.row];
    cell.textLabel.text = m;
    cell.accessoryType = UITableViewCellSelectionStyleBlue;
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        
        [hud setCaption:@"正在下载..."];
        [hud setProgress:0.08];
        [hud show];
    }
    else if (indexPath.row==1)
    {
        for (ASIHTTPRequest *r in [_queue operations]) {
            NSString *fileName = [r.userInfo objectForKey:@"Name"];
            if ([fileName isEqualToString:name]) {
                //队列中已存在特定request时，退出
                return;
            }
        }
        NSString *_url = @"http://downloads.sourceforge.net/sevenzip/7za920.zip";
        NSURL *url = [NSURL URLWithString:_url];
        _request = [ASIHTTPRequest requestWithURL:url];
        _request.delegate = self;
        _request.temporaryFileDownloadPath = [self cachesPath];
        _request.downloadDestinationPath = [self actualSavePath];
        _request.downloadProgressDelegate = self;
        _request.allowResumeForFileDownloads = YES;
        _request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"Name", nil];
        [_queue addOperation:_request];
        
        [hud setCaption:@"正在下载..."];
        [hud setProgress:0.05];
        [hud show];
    }
    else if (indexPath.row==2)
    {
        [sgdownload startWithDelegate:self];
        [hud setCaption:@"正在下载..."];
        [hud setProgress:0.05];
        [hud show];
    }
    else if(indexPath.row==3)
    {
        EpointAVCallViewController *v = [[EpointAVCallViewController alloc]init];
        [self.navigationController pushViewController:v animated:YES];
    }
    else if (indexPath.row==4)
    {
        
    }
    else if (indexPath.row==5)
    {
        EpointAppDelegate *dele = [[UIApplication sharedApplication]delegate];
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 64)];
        [btn setTitle:@"TestWindow" forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor redColor]];
        [dele.window addSubview:btn];
    }
    else if (indexPath.row==6)
    {
        EpointCDViewController *vc = [[EpointCDViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row==7)
    {
        EpointPerson *person = [[EpointPerson alloc]init];
        person.name = @"李亚春";
        person.address = @"张家港";
        [person save];
        EpointPerson *p2 = (EpointPerson*)[EpointPerson findFirstByCriteria:@""];
        debuglog(@"%@",p2.name);
    }
    else if (indexPath.row==8)
    {
        EpointTestiChartjsViewController *vc = [[EpointTestiChartjsViewController alloc]init];
       [self.navigationController pushViewController:vc animated:YES];
//        DetailViewController *vc = [[DetailViewController alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row==9)
    {
        NSArray *arr = [NSArray arrayWithObjects:@"中国",@"韩国",@"朝鲜",@"美国", nil];
        [EpointMutiPickerViewController InvokeMutiPickerViewController:self title:@"国家选择" strArr:arr handler:^(NSMutableArray *indexArr)
         {
             NSMutableString *sb = [[NSMutableString alloc]init];
             for (int i=0; i<indexArr.count; i++) {
             NSNumber *num = [indexArr objectAtIndex:i];
             NSString *s = [arr objectAtIndex:num.intValue];
             [sb appendString:s];
             }
             [self toastMessage:sb];
         }];
    }
}

-(void)SGDownloadProgress:(float)progress Percentage:(NSInteger)percentage
{
    [hud setProgress:progress];
}

-(void)SGDownloadFinished:(NSData*)fileData
{
    fileData = nil;
    sgdownload = nil;
}
-(void)SGDownloadFail:(NSError*)error{
    
}


-(void)setProgress:(float)newProgress
{
    
    if (newProgress>0.05) {
        [hud setProgress:newProgress];
    }
    if (newProgress>=1) {
        [hud hide];
    }
}

-(NSString *)actualSavePath{
    return [self.getPathOfDocuments stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", name, @"zip"]];
}
-(NSString *)cachesPath{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", name, @"zip"]];
    return path;
}

-(NSString *)getPathOfDocuments{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    return path;
}

- (void)tick:(NSTimer *)timer {
	static CGFloat p = 0.08;
	p += 0.01;
	[hud setProgress:p];
	if (p >= 1) {
		p = 0;
		[timer invalidate];
		[hud hide];
		[self performSelector:@selector(resetProgress) withObject:nil afterDelay:0.2];
	}
}

- (void)resetProgress {
	[hud setProgress:0];
}

@end
